package com.dbh.alg.datastructure.queue;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

/**
 * 二叉树层序遍历
 * @author 董帮辉
 * @date 2025/5/17
 **/
public class E02Leetcode103 {

    /**
     *  二叉树锯齿形层序遍历
     * @param root 根节点
     * @return 遍历后的集合
     */
    public List<List<Integer>> levelOrder(TreeNode root) {
        List<List<Integer>> list = new ArrayList<>();
        if (root == null) {
            return list;
        }
        Queue<TreeNode> queue = new LinkedListQueue<>();
        queue.offer(root);
        boolean odd = true;
        int c1 = 1; // 当前层节点数
        while(!queue.isEmpty()) {
            int c2 = 0; // 下一层节点数
            LinkedList<Integer> level = new LinkedList<>(); // 保存每一层结果
            for (int i = 0; i< c1; i++) {
                TreeNode poll = queue.poll();
                if (odd) {
                    level.offerLast(poll.val);
                } else {
                    level.offerFirst(poll.val);
                }
                if (poll.left != null) {
                    queue.offer(poll.left);
                    c2++;
                }
                if (poll.right != null) {
                    queue.offer(poll.right);
                    c2++;
                }
            }
            odd = !odd;
            System.out.println();
            c1 = c2;
            list.add(level);
        }
        return list;
    }
}
